package com.monitor.security;

import com.monitor.network.HttpClient;
import com.monitor.network.JsonUtil;
import com.monitor.network.RegistrationResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JOptionPane;

/**
 * 注册管理器，用于处理系统注册信息的验证和保存
 */
public class RegistrationManager {
    private static final String CONFIG_FILE = "registration.properties";
    private static final String REGISTRATION_KEY = "registered";
    private static final String REGISTRATION_CODE_KEY = "registration_code";
    private static final String COMPANY_KEY = "deptName";
    private static final String EMAIL_KEY = "email";
    private static final String PHONE_KEY = "phone";
    private static final String SECURITY_QUESTION_KEY = "security_question";
    private static final String SECURITY_ANSWER_KEY = "security_answer";
    private static final String DEVICE_ID_KEY = "device_id";
    private static final String TOKEN_KEY = "token";
    private static final String REFRESH_TOKEN_KEY = "refresh_token";
    
    // 注册API地址通过ApiConfig类获取
    
    private boolean registered;
    private String registrationCode;
    private String deptName;
    private String email;
    private String phone;
    private String securityQuestion;
    private String securityAnswer;
    private String deviceId;
    private String token;
    private String refreshToken;
    private File configFile;
    
    /**
     * 获取设备ID
     * @return 设备ID
     */
    public String getDeviceId() {
        return deviceId;
    }
    
    
    public RegistrationManager() {
        // 初始化配置文件路径
        String userHome = System.getProperty("user.home");
        String configDir = userHome + File.separator + ".monitor";
        new File(configDir).mkdirs(); // 确保目录存在
        configFile = new File(configDir, CONFIG_FILE);
        
        // 加载注册信息
        loadRegistrationInfo();
    }
    /**
     * 加载注册信息
     */
    private void loadRegistrationInfo() {
        if (!configFile.exists()) {
            // 如果配置文件不存在，设置为未注册状态
            registered = false;
            return;
        }
        
        // 从配置文件加载注册信息
        Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream(configFile)) {
            props.load(fis);
            String registeredStr = props.getProperty(REGISTRATION_KEY);
            registered = "true".equals(registeredStr);
            
            if (registered) {
                registrationCode = props.getProperty(REGISTRATION_CODE_KEY);
                deptName = props.getProperty(COMPANY_KEY);
                email = props.getProperty(EMAIL_KEY);
                phone = props.getProperty(PHONE_KEY);
                securityQuestion = props.getProperty(SECURITY_QUESTION_KEY);
                securityAnswer = props.getProperty(SECURITY_ANSWER_KEY);
                deviceId = props.getProperty(DEVICE_ID_KEY);
                token = props.getProperty(TOKEN_KEY);
                refreshToken = props.getProperty(REFRESH_TOKEN_KEY);
            }
        } catch (IOException e) {
            e.printStackTrace();
            registered = false;
        }
    }
    
    /**
     * 保存注册信息到配置文件
     */
    private void saveRegistrationInfo() {
        Properties props = new Properties();
        props.setProperty(REGISTRATION_KEY, String.valueOf(registered));
        
        if (registered) {
            props.setProperty(REGISTRATION_CODE_KEY, registrationCode != null ? registrationCode : "");
            props.setProperty(COMPANY_KEY, deptName != null ? deptName : "");
            props.setProperty(EMAIL_KEY, email != null ? email : "");
            props.setProperty(PHONE_KEY, phone != null ? phone : "");
            props.setProperty(SECURITY_QUESTION_KEY, securityQuestion != null ? securityQuestion : "");
            props.setProperty(SECURITY_ANSWER_KEY, securityAnswer != null ? securityAnswer : "");
            props.setProperty(DEVICE_ID_KEY, deviceId != null ? deviceId : "");
            props.setProperty(TOKEN_KEY, token != null ? token : "");
            props.setProperty(REFRESH_TOKEN_KEY, refreshToken != null ? refreshToken : "");
        }
        
        try (FileOutputStream fos = new FileOutputStream(configFile)) {
            props.store(fos, "Monitor Registration Configuration");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 检查系统是否已注册
     * @return 如果已注册返回true，否则返回false
     */
    public boolean isRegistered() {
        return registered;
    }
    
    /**
     * 注册系统（兼容旧版本，不包含设备类型）
     * @param registrationCode 注册码
     * @param company 公司/单位名称
     * @param email 电子邮件
     * @param phone 电话号码
     * @param securityQuestion 安全问题
     * @param securityAnswer 安全问题答案
     * @return 如果注册成功返回true，否则返回false
     */
    public boolean register(String registrationCode, String company, String email, 
                           String phone, String securityQuestion, String securityAnswer) {
        // 调用包含设备类型的方法，默认设备类型为null
        return register(registrationCode, company, email, phone, securityQuestion, securityAnswer, null);
    }
    
    /**
     * 注册系统
     * @param registrationCode 注册码
     * @param company 公司/单位名称
     * @param email 电子邮件
     * @param phone 电话号码
     * @param securityQuestion 安全问题
     * @param securityAnswer 安全问题答案
     * @param deviceType 设备类型（可选，0表示一体机，1表示机房设备，2表示教师设备）
     * @return 如果注册成功返回true，否则返回false
     */
    public boolean register(String registrationCode, String company, String email, 
                           String phone, String securityQuestion, String securityAnswer, Integer deviceType) {
        return register(registrationCode, company, email, phone, securityQuestion, securityAnswer, deviceType, null,null);
    }
    
    /**
     * 注册系统（包含系统硬件信息）
     * @param registrationCode 注册码
     * @param company 公司/单位名称
     * @param email 电子邮件
     * @param phone 电话号码
     * @param securityQuestion 安全问题
     * @param securityAnswer 安全问题答案
     * @param deviceType 设备类型（可选，0表示一体机，1表示机房设备，2表示教师设备）
     * @param systemInfo 系统硬件信息
     * @return 如果注册成功返回true，否则返回false
     */
    public boolean register(String registrationCode, String company, String email, 
                           String phone, String securityQuestion, String securityAnswer, 
                           Integer deviceType, java.util.Map<String, String> systemInfo,String remark) {
        // 验证注册信息
        if (registrationCode == null || registrationCode.trim().isEmpty()) {
            return false;
        }
        
        // 验证注册码格式（这里可以添加更复杂的验证逻辑）
        if (!isValidRegistrationCode(registrationCode)) {
            return false;
        }
        
        try {
            // 构建请求数据
            String jsonData = JsonUtil.toJson(registrationCode, company, email, 
                                           phone, securityQuestion, securityAnswer, deviceType, systemInfo, remark);
            
            // 发送注册请求
            String apiUrl = com.monitor.network.ApiConfig.getRegisterApiUrl();
            String responseJson = HttpClient.post(apiUrl, jsonData);
            
            // 解析响应数据
            RegistrationResponse response = JsonUtil.parseRegistrationResponse(responseJson);
            
            if (response != null && response.isSuccess()) {
                // 注册成功，保存注册信息
                this.registered = true;
                this.registrationCode = registrationCode;
                this.deptName = company;
                this.email = email;
                this.phone = phone;
                this.securityQuestion = securityQuestion;
                this.securityAnswer = securityAnswer;
                
                // 保存从服务器返回的信息
                if (response.getData() != null) {
                    this.deviceId = response.getData().getDeviceId();
                    this.token = response.getData().getToken();
                    this.refreshToken = response.getData().getRefreshToken();
                }
                
                // 保存注册信息
                saveRegistrationInfo();
                return true;
            } else {
                // 注册失败，显示错误信息
                String errorMsg = (response != null) ? response.getMsg() : "未知错误";
                JOptionPane.showMessageDialog(null, "注册失败: " + errorMsg, 
                                            "注册错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }
        } catch (IOException e) {
            // 处理网络异常
            JOptionPane.showMessageDialog(null, "网络连接错误: " + e.getMessage(), 
                                        "连接错误", JOptionPane.ERROR_MESSAGE);
            
            // 如果网络连接失败，尝试本地注册（离线模式）
            boolean offlineRegister = JOptionPane.showConfirmDialog(null, 
                    "网络连接失败，是否尝试离线注册？\n(离线注册后需要在有网络时重新注册)", 
                    "离线注册", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
            
            if (offlineRegister) {
                // 离线注册逻辑
                this.registered = true;
                this.registrationCode = registrationCode;
                this.deptName = company;
                this.email = email;
                this.phone = phone;
                this.securityQuestion = securityQuestion;
                this.securityAnswer = securityAnswer;
                
                // 保存注册信息
                saveRegistrationInfo();
                return true;
            }
            
            return false;
        }
    }
    
    /**
     * 验证注册码是否有效
     * @param code 注册码
     * @return 如果有效返回true，否则返回false
     */
    private boolean isValidRegistrationCode(String code) {
        // 这里可以实现更复杂的注册码验证逻辑
        // 例如，检查注册码格式、长度、校验和等
        return code.length() >= 5;
    }
    
    /**
     * 获取注册码
     * @return 注册码
     */
    public String getRegistrationCode() {
        return registrationCode;
    }
    
    /**
     * 获取公司/单位名称
     * @return 公司/单位名称
     */
    public String getCompany() {
        return deptName;
    }
    
    /**
     * 获取电子邮件
     * @return 电子邮件
     */
    public String getEmail() {
        return email;
    }
    
    /**
     * 获取电话号码
     * @return 电话号码
     */
    public String getPhone() {
        return phone;
    }
    
    /**
     * 获取安全问题
     * @return 安全问题
     */
    public String getSecurityQuestion() {
        return securityQuestion;
    }
    
    /**
     * 获取安全问题答案
     * @return 安全问题答案
     */
    public String getSecurityAnswer() {
        return securityAnswer;
    }
    
    /**
     * 重置注册信息
     */
    public void resetRegistration() {
        registered = false;
        registrationCode = null;
        deptName = null;
        email = null;
        phone = null;
        securityQuestion = null;
        securityAnswer = null;
        deviceId = null;
        token = null;
        refreshToken = null;
        saveRegistrationInfo();
    }
    

    
    /**
     * 获取认证令牌
     * @return 认证令牌
     */
    public String getToken() {
        return token;
    }
    
    /**
     * 获取刷新令牌
     * @return 刷新令牌
     */
    public String getRefreshToken() {
        return refreshToken;
    }
}